package com.ysm.smfu.utils;

import java.io.UnsupportedEncodingException;
import java.util.Hashtable;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.ysm.smfu.R;

public class QRUtil {

    private static final int BLACK = 0xff000000;

    /**
     * 生成中间带logo的二维码
     *
     * @param url
     * @param logo
     * @param widthAndHeight
     * @return
     * @throws WriterException
     */
    public static Bitmap createQRCode(String url, Bitmap logo, int widthAndHeight) throws WriterException {
        //网址生成URL
        if ((url.toLowerCase().startsWith("http") || url.toLowerCase()
                .startsWith("https"))) {
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix matrix = new MultiFormatWriter().encode(url,
                    BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);
            int width = matrix.getWidth();
            int height = matrix.getHeight();
            int[] pixels = new int[width * height];

            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (matrix.get(x, y)) {
                        pixels[y * width + x] = BLACK;
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(width, height,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return addLogo(bitmap, logo);
        } else {
//            非网址生成URL,名片类似
            try {
                return cretaeBitmap(new String(url.getBytes(),
                        "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                System.err.println("异常："+e.getMessage());
                return BitmapFactory.decodeResource(UIUtils.getResources(), R.mipmap.start);
            }
        }
    }

    /**
     * 生成二维码
     *
     * @param str
     * @return Bitmap
     * @throws WriterException
     */
    public static Bitmap cretaeBitmap(String str) throws WriterException {
        // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
        BitMatrix matrix = new MultiFormatWriter().encode(str,
                BarcodeFormat.QR_CODE, 300, 300);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        // 二维矩阵转为一维像素数组,也就是一直横着排了
        int halfW = width / 2;
        int halfH = height / 2;
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = 0xff000000;
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        // 通过像素数组生成bitmap
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

        return bitmap;
    }

    /**
     * 在二维码中间添加Logo图案
     */
    public static Bitmap addLogo(Bitmap qrCodeBitmap, Bitmap logo) {
        if (qrCodeBitmap == null || logo == null) {
            return null;
        }
        Bitmap roundBitmap = CircleUtil.toRoundBitmap(UIUtils.getContext(), logo);
        //获取图片的宽高
        int srcWidth = qrCodeBitmap.getWidth();
        int srcHeight = qrCodeBitmap.getHeight();
        int logoWidth = roundBitmap.getWidth();
        int logoHeight = roundBitmap.getHeight();


        //logo大小为二维码整体大小的1/5
        float scaleFactor = srcWidth / 4 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, qrCodeBitmap.getConfig());
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(qrCodeBitmap, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);

            canvas.save(Canvas.ALL_SAVE_FLAG);
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }

        return bitmap;
    }

}
